//
//  AddCarViewController.m
//  FuelLog
//
//  Created by Pure Mass Communications on 9/8/08.
//  Copyright 2008 . All rights reserved.
//
//  Placed under GPL v2 with the kind permission of Pure Mass Communications
//
//  Modified to make compile under SDK 3.1 by Olaf Greck in May 2010
//
//
//  This program is free software; you can redistribute it and/or
//  modify it under the terms of the GNU General Public License
//  as published by the Free Software Foundation; either version 2
//  of the License, or (at your option) any later version.

//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.

//  You should have received a copy of the GNU General Public License
//  along with this program; if not, write to the Free Software
//  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

#import "AddCarViewController.h"
#import "FuelLogAppDelegate.h"
#import "FuelLogViewController.h"
#import "CarsViewController.h"
#import "LoginViewController.h"
#import "DebugOutput.h"

@implementation AddCarViewController

@synthesize car;
@synthesize deleteButton, exportButton;

- (void)reallyDelete {
	if (car.pk != -1) {
		FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
		[appDelegate removeCar:car];
	}
	[self cancel:nil];
}

#pragma mark UIAlertView

- (void)alertDeleteCancelAction
{
	// open a alert with an OK and cancel button
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" 
													message:(NSLocalizedString( @"AddCar_alertDeleteCancelAction msg", @"Delete this car and all of its fuel entries?"))
												   delegate:self 
										  cancelButtonTitle:(NSLocalizedString(@"AddCar_alertDeleteCancelAction Cancel",@"Cancel")) 
										  otherButtonTitles:(NSLocalizedString(@"AddCar_alertDeleteCancelAction other",@"Yes, Delete")), nil];
	[alert show];
	[alert release];
}

#pragma mark UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if (buttonIndex == [alert cancelButtonIndex]) {
		return;
	}
	[self reallyDelete];
}

#pragma mark Alert
- (void)alertFail:(NSString *)errorMsg {
	// open a alert with an OK
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" 
													message:errorMsg
												   delegate:self 
										  cancelButtonTitle:(NSLocalizedString(@"AddCar_alertFail OK",@"OK")) 
										  otherButtonTitles:nil];
	[alert show];
	[alert release];
}

#pragma mark UIViewController

/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
	if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
		// Initialization code
	}
	return self;
}
*/
 
/*
 Implement loadView if you want to create a view hierarchy programmatically
- (void)loadView {
}
 */

- (void)viewDidLoad {
	carBox.text = car.label;
	carBox.clearButtonMode = UITextFieldViewModeWhileEditing; 
	[self.exportButton useSystemTouchStyle];
 	[self.deleteButton useRedDeleteStyle];  
 }

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	[self setLabel];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations
	return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
	// Release anything that's not essential, such as cached data
}


- (void)dealloc {
	[carBox dealloc]; 
	[deleteButton dealloc];
	[super dealloc];
}

- (IBAction)cancel:(id)sender { 
	[car release];
	[carBox resignFirstResponder];
	[self dismissModalViewControllerAnimated:YES];
	CarsViewController *cvc = (CarsViewController *)self.parentViewController;
	[cvc clickSelectedCar];
}

- (IBAction)done:(id)sender {
	NSString *name = [carBox.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
	[carBox setText:name];
	if ([name length] == 0) { 
		 [self alertFail:(NSLocalizedString(@"AddCar_errorText enter label.",@"Please enter a label.")) ];
		return;
	}
	BOOL changed = ![name isEqualToString:car.label];
    FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
	if ((car.pk <= 0 || changed) && [appDelegate hasCar:name]) { 
		 [self alertFail:(NSLocalizedString(@"AddCar_errorText same label",@"Another car has the same label. Please enter a different label.")) ];
		return;
	}
	[car setLabel:name]; 
	if (car.pk == -1) {
		[appDelegate addCar:car];
	}
	[car release];
	[carBox resignFirstResponder];
	[self dismissModalViewControllerAnimated:YES];
	CarsViewController *cvc = (CarsViewController *)self.parentViewController;
	[cvc clickSelectedCar];
}

- (IBAction)deleteCar:(id)sender {
	[self alertDeleteCancelAction];
}

- (IBAction)exportCar:(id)sender {
	debug(@"in exportCar");
	LoginViewController *loginController = [FuelLogViewController loginViewController];
	[loginController setMode:FUELLOG_EXPORT];
	[loginController setCar:car];
	[self presentModalViewController:loginController animated:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
	NSString *name = [carBox.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
	[carBox setText:name];
	if ([name length] == 0) { 
		 [self alertFail:(NSLocalizedString(@"AddCar_textFieldShouldReturn enter label.",@"Please enter a label.")) ];
		return NO;
	}
	BOOL changed = ![name isEqualToString:car.label];
    FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
	if ((car.pk <= 0 || changed) && [appDelegate hasCar:name]) { 
		 [self alertFail:(NSLocalizedString(@"AddCar_textFieldShouldReturn same label",@"Another car has the same label.\nPlease enter a different label.")) ];
		return NO;
	} 
	[carBox resignFirstResponder];
	return YES;
}

- (void)setLabel {
	if (car.pk == -1) {
		deleteButton.hidden = YES;
		exportButton.hidden = YES;
	} else {
		deleteButton.hidden = NO;
		exportButton.hidden = NO;
	}
	[carBox setText:car.label]; 
}

@end
